package com.lostad.app.vert.websocket;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.lostad.app.vert.util.JacksonUtil;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.ServerWebSocket;
import io.vertx.core.shareddata.LocalMap;

/*
 * http://www.tuicool.com/articles/6b6Rfq
 * @author <a href="http://tfox.org">Tim Fox</a>
 */
public class WebSocketVerticle extends AbstractVerticle{
	public static final String FOEMAT_CHAT = "/chat/(\\w+)(/?)";
	private HttpServer server ;
    
	public WebSocketVerticle(HttpServer server) {
      this.server = server;
	}
    
	@Override
	public void start() throws Exception {
		//websocket请求处理
		server.websocketHandler(new Handler<ServerWebSocket>() {
			@Override
			public void handle(ServerWebSocket event) {
				String path = event.path();
				Matcher matcher = Pattern.compile(FOEMAT_CHAT).matcher(path);
				if (!matcher.matches()) {
					event.reject();//拒绝不合规则的请求
					return;
				}
				
				final String chatRoomId = matcher.group(1);
				final String clientId = event.textHandlerID();
				// 上线记录
				LocalMap localMap = vertx.sharedData().getLocalMap(chatRoomId);//
				localMap.put(clientId, clientId);
				System.out.print(localMap.size()+"人在线++++++++上线" + clientId);
				
				event.handler(buff->{//消息处理
					try {
						String msg = buff.toString();
						Map bean = new HashMap<>();
						
						if(msg.contains("hello")){
							bean.put("msg",localMap.size()+"人在线！---你好:clientId"+clientId);
							String json = JacksonUtil.toJson(bean);
							event.writeBinaryMessage(Buffer.buffer(json));
						}else{
							bean.put("msg",localMap.size()+"人在线---你大爷 Client!!!"+clientId );
							String json = JacksonUtil.toJson(bean);
							//event.writeBinaryMessage(Buffer.buffer(json));
							event.writeFinalTextFrame(json);
						}
						
					} catch (Exception e) {
						event.reject();
					}
					
				});
				
				event.closeHandler(buff->{//关闭
					vertx.sharedData().getLocalMap(chatRoomId).remove(clientId);
					System.out.print("-----------下线" + clientId);
				});
			}// end handle
		});
		
	}
	
	
	
}
